"""
Case Type   : 资源池化
Case Name   : gs_collector 数据库主机点实例异常
Create At   : 2024.01
Owner       : chen
Description :
    数据库主机点实例异常
Expect      :
    收集成功
"""

import os
import unittest
import datetime
import time
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from yat.test import Node
from yat.test import macro


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.com = Common('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.log_path = os.path.join(os.path.dirname(macro.PG_LOG_PATH))
        self.config_path = os.path.join(self.log_path, 'collector_config.json')

    def test_shared_storage(self):
        current_time = datetime.datetime.now()
        start_time = current_time.strftime('%Y%m%d %H:%M')
        end_time = (current_time + datetime.timedelta(minutes=5)).strftime('%Y%m%d %H:%M')
        text = '-----step1: 数据库主机点实例异常' \
            ' expect: 收集成功-----'
        self.log.info(text)

        self.log.info('-----查看主机名称-----')
        check_cmd = f'hostname'
        self.log.info(check_cmd)
        hostname = self.pri_node.sh(check_cmd).result()
        self.log.info(hostname)

        self.log.info('-----创建配置文件, 内容为json格式-----')
        json_str = r'''{{"Collect":[{{"TypeName": "Log", "Content":
            "DataNode,ClusterManager","Interval":"0", "Count":"1", "FileNumber":"0"}}]}}'''
        cmd = f'''echo '{json_str}' > {self.config_path}'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)

        self.log.info('-----构建实例故障-----')
        for i in range(6):
            self.log.info(f'-----第 {i+1} 次杀掉dn进程-----')
            pid = self.com.get_pid(self.pri_node, 'bin/gaussdb')
            self.pri_node.sh(f'kill -9 {pid}').result()
            time.sleep(5)

        self.log.info('-----收集信息-----')
        cmd = f'source {macro.DB_ENV_PATH};' \
            f'gs_collector --begin-time="{start_time}" --end-time="{end_time}" -h {hostname} ' \
            f'-C {self.config_path}'
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn(self.constant.GS_COLLECTOR_SUCCESS_MSG, res)

        self.log.info('-----查看结果-----')
        collector_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'cd {self.log_path}; ls;tar -zxvf collector*.tar.gz;'
        self.log.info(collector_cmd)
        res = self.pri_node.sh(collector_cmd).result()
        self.log.info(res)
        self.assertIn('Summary.log', res)
        self.assertIn('Detail.log', res)
        self.assertIn(f'{hostname}.tar.gz', res)

    def tearDown(self):
        self.log.info('-----step2:清理、恢复环境-----')
        rm_cmd = f'cd {self.log_path}/; rm -rf collector_*'
        self.log.info(rm_cmd)
        res = self.pri_node.sh(rm_cmd).result()
        self.log.info(res)
        self.log.info('-----重启数据库-----')
        res = self.pri_sh.exec_cm_ctl('stop && cm_ctl start')
        self.log.info(res)
        self.assertIn(self.constant.cm_start_success_msg, res)
        status = self.pri_sh.exec_cm_ctl('switchover', '-a')
        self.log.info(status)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')